package com.xinpu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinpu.entity.TCompany;
import com.xinpu.entity.TSales;
import com.xinpu.entity.TSalesTaskMap;
import com.xinpu.entity.TTask;
import com.xinpu.vo.ResponseMessage;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
public class TaskSchedule {
    @Autowired
    private ITSalesTaskMapService itSalesTaskMapService;
    @Autowired
    private ITTaskService itTaskService;
    @Autowired
    private ITSalesService itSalesService;
    @Autowired
    private ITCompanyService itCompanyService;


    @Scheduled(cron = "0 0 0 * * ?")
    public void releaseTask() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        ThreadContext.bind(manager);
        List<TCompany> tCompanyList = itCompanyService.list();
        for (TCompany tCompany : tCompanyList) {
            QueryWrapper<TTask> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tenant_id", tCompany.getTenantId());
            List<TTask> tTasks = itTaskService.list(queryWrapper);
            if (tTasks.size() != 0) {
                for (TTask tTask : tTasks) {
                    QueryWrapper<TSales> wrapper = new QueryWrapper<>();
                    wrapper.eq("status", 0);
                    wrapper.eq("tenant_id", tTask.getTenantId());
                    List<TSales> list = itSalesService.list(wrapper);
                    for (TSales tSales : list) {
                        TSalesTaskMap taskMap = new TSalesTaskMap();
                        taskMap.setSid(tSales.getId());
                        taskMap.setDueTime(LocalDateTime.now());
                        taskMap.setTaskId(tTask.getId());
                        taskMap.setNum(0);
                        taskMap.setStatus(0);
                        itSalesTaskMapService.save(taskMap);
                    }
                }
            }
        }
    }
}
